package com.lyj.service.impl;

import com.lyj.dataobject.ProductInfo;
import com.lyj.dto.CartDTO;
import com.lyj.enums.ProductStatusEnum;
import com.lyj.enums.ResultEnum;
import com.lyj.exception.SellException;
import com.lyj.repository.ProductInfoRepository;
import com.lyj.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by lyj on 2017/10/13.
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductInfoRepository repository;

    @Override
    public ProductInfo findOne(String productId) {
        return repository.findOne(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return repository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return repository.save(productInfo);
    }

    /**
     * 加库存
     * @param cartDTOList
     */
    @Override
    @Transactional
    public void increaseStock(List<CartDTO> cartDTOList) {

        for (CartDTO cartDTO:cartDTOList){
            ProductInfo productInfo=repository.findOne(cartDTO.getProductId());
            if (productInfo==null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer result=productInfo.getProductStock()+cartDTO.getProductQuantity();
            productInfo.setProductStock(result);

            repository.save(productInfo);
        }
    }

    /**
     * 减库存
     * @param cartDTOList
     */
    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO:cartDTOList){
            //根据购物车的商品id查询是否有改商品
           ProductInfo productInfo = repository.findOne(cartDTO.getProductId());
           if(productInfo==null){
               throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
           }
           //用数据库的库存数-商品的购买数量
          Integer result = productInfo.getProductStock()-cartDTO.getProductQuantity();
           if (result<0){
               throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
           }
           productInfo.setProductStock(result);

           repository.save(productInfo);
        }
    }
}
